import axios from "axios";
import type { AxiosInstance } from "axios";
import type { RHRequresHooks, RHResquestConfig } from "./type";

import { ElLoading } from "element-plus";
import { LoadingInstance } from "element-plus/lib/components/loading/src/loading";

const DEFAULT_LAODINNG = true;
class RHRequest {
  instance: AxiosInstance;
  interceptors?: RHRequresHooks;
  showLoading?: boolean;

  constructor(config: RHResquestConfig) {
    // 创建axios实例
    this.instance = axios.create(config);
    //保存一些基本的信息
    this.showLoading = config.showLoading ?? DEFAULT_LAODINNG;
    this.interceptors = config.interceptors;

    // 从config里面取出的拦截去是对应的实例的拦截器
    this.instance.interceptors.request.use(
      this.interceptors?.requestInterceptor,
      this.interceptors?.requestInterceptorCatch
    );
    this.instance.interceptors.response.use(
      this.interceptors?.responseInterceptor,
      this.interceptors?.requestInterceptorCatch
    );

    // 添加所有实例都有的拦截器
    this.instance.interceptors.request.use(
      (config: RHResquestConfig): RHResquestConfig => {
        return config;
      },
      (error) => {
        return error;
      }
    );
    this.instance.interceptors.response.use(
      (res) => {
        const data = res.data;
        if (data.returnCode === "-1001") {
          console.log("请求失败,错误信息");
        } else {
          return res.data;
        }
      },
      (error) => {
        if (error.response.status === "404") {
          alert("404错误");
        }
        return error;
      }
    );
  }
  request<T>(config: RHResquestConfig): Promise<T> {
    return new Promise((resolve, rejected) => {
      // 1.单个请求时队请求的config的处理
      if (config.interceptors?.requestInterceptor) {
        config = config.interceptors.requestInterceptor(config);
      }

      // 2.判断是否需要显示loading
      if (config.showLoading === false) {
        this.showLoading = config.showLoading;
      }

      // 每个请求的拦截器
      this.instance
        .request<any, T>(config)
        .then((res: any) => {
          // 1.单个请求数据的梳理
          if (config.interceptors?.requestInterceptor) {
            res = config.interceptors.requestInterceptor(res);
          }
          // 2.将showloading设置为true 这样不会影响到下一个请求
          this.showLoading = DEFAULT_LAODINNG;

          // 3.直接将结果返回回去
          resolve(res);
        })
        .catch((error) => {
          this.showLoading = DEFAULT_LAODINNG;
          rejected(error);
          return error;
        });
    });
  }
}

export default RHRequest;
